package com.jemmyee.cms.web.controller.admin;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.json.simple.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.jemmyee.cms.entity.ProductBrand;
import com.jemmyee.cms.web.CmsConstants;
import com.jemmyee.cms.web.controller.kernel.BaseCmsController;
import com.jemmyee.core.dao.Page;
import com.jemmyee.core.utils.DateUtils;
import com.jemmyee.core.utils.FileUtils;
import com.jemmyee.core.web.Constants;
import com.jemmyee.core.web.utils.MathUtils;

/**
 * @Description:产品
 * @author:jemmyee@gmail.com
 * @date:2011-8-24
 * @version:v1.0
 */
@Controller("productBrandController")
@RequestMapping(Constants.MV_URI_APP_CMS+Constants.MV_URI_MAIN_ADMIN+Constants.SYM_PATH_SEPARATOR+CmsConstants.ENTITY_PRODUCT_BRAND)
public class ProductBrandController extends BaseCmsController {

	private static Log log = LogFactory.getLog(ProductBrandController.class);
	/* 分页查出保存的条件 */
	private static final String ENTITY_SESSION_BEAN = "admin_session_bean_"
			+ MathUtils.getRandomDouble();
	
	private static final String ROOT_VIEW =Constants.MV_URI_MAIN_ADMIN+Constants.MV_URI_APP_CMS+Constants.SYM_PATH_SEPARATOR+CmsConstants.ENTITY_PRODUCT_BRAND;
	private static final String ROOT_URI=Constants.MV_URI_APP_CMS+Constants.MV_URI_MAIN_ADMIN+Constants.SYM_PATH_SEPARATOR+CmsConstants.ENTITY_PRODUCT_BRAND;


	@RequestMapping(Constants.MV_URI_COMM_TOADD)
	public ModelAndView toAdd(HttpServletRequest request) {
		ModelAndView mv = new ModelAndView();
		initToAdd(mv,ROOT_URI, ROOT_VIEW);
		return mv;
	}

	@RequestMapping(Constants.MV_URI_COMM_TOEDIT + "/{id}")
	public ModelAndView toEdit(@PathVariable String id) {
		ModelAndView mv = new ModelAndView();
		ProductBrand item = productBrandService.findById(id);
		initToEdit(mv, item,ROOT_URI, ROOT_VIEW);
		return mv;
	}
	/**
	* @Description:图标上传 页面
	* @author:jemmyee@gmail.com
	* @date:2011-8-27
	*/
	@RequestMapping("/toUpload")
	public ModelAndView toUpload(HttpServletRequest request) {
		ModelAndView mv = new ModelAndView();
	    mv.addObject(Constants.MV_OBJECT_ROOT_URI,ROOT_URI);
		mv.setViewName(ROOT_VIEW+"/upload");
		return mv;
	}

	@RequestMapping(Constants.MV_URI_COMM_ADD)
	@ResponseBody
	public Map<String, Object> add(@RequestBody ProductBrand bean,
			HttpServletRequest request) {
		Map<String, Object> model = new HashMap<String, Object>();
		ProductBrand temp = null;
		try {
			if (productBrandService.findByProperty("name", bean.getName()) != null
					&& productBrandService.findByProperty("name", bean.getName())
							.size() > 0) {
				temp = productBrandService.findByProperty("name", bean.getName())
						.get(0);
			}
			if (temp != null && temp.getName().equals(bean.getName().trim())) {
				model.put(Constants.AJAX_MSG_NAME, Constants.AJAX_MSG_RENAME);
			} else {
				bean.setName(bean.getName().trim());
				bean.setAddTime(new Date());
				bean.setSortOrder(100);
				bean.setShowIndex((short)0);
//				 bean.setIsDelete((short)0);
				productBrandService.save(bean);
				model.put(Constants.AJAX_MSG_NAME, Constants.AJAX_MSG_SUCC);
			}

		} catch (Exception e) {
			model.put(Constants.AJAX_MSG_NAME, Constants.AJAX_MSG_ERROR);
			log.error(e);
		}

		return model;
	}

	@RequestMapping(Constants.MV_URI_COMM_EDIT)
	@ResponseBody
	public Map<String, Object> edit(@RequestBody ProductBrand bean,
			HttpServletRequest request) {
		Map<String, Object> model = new HashMap<String, Object>();
		try {
			ProductBrand temp = productBrandService.findById(bean.getId());
			List<ProductBrand> temps = productBrandService.findByProperty("name", bean
					.getName().trim());
			if (temps.size() > 0
					&& !temps.get(0).getName().equals(temp.getName().trim())) {
				model.put(Constants.AJAX_MSG_NAME, Constants.AJAX_MSG_RENAME);
			} else {
				temp.setName(bean.getName().trim());
				temp.setBrief(bean.getBrief());
				temp.setImg(bean.getImg());
				temp.setIndate(bean.getIndate());
				temp.setOwner(bean.getOwner());
				temp.setUseRang(bean.getUseRang());
				temp.setType(bean.getType());
				temp.setTradeType(bean.getTradeType());
				if(bean.getOwnerAddress()!=null)
				{
					temp.setOwnerAddress(bean.getOwnerAddress());
				}
				if(bean.getOwnerTel()!=null)
				{
					temp.setOwnerTel(bean.getOwnerTel());
				}
				if(bean.getPrice()!=null)
				{
					temp.setPrice(bean.getPrice());
				}
				temp.setSn(bean.getSn());
				// bean.setIsDelete(temp.getIsDelete());
				productBrandService.update(temp);
				model.put(Constants.AJAX_MSG_NAME, Constants.AJAX_MSG_SUCC);
			}
		} catch (Exception e) {
			model.put(Constants.AJAX_MSG_NAME, Constants.AJAX_MSG_ERROR);
			log.error(e);
		}
		return model;
	}

	@RequestMapping(Constants.MV_URI_COMM_DELETE + "/{id}")
	@ResponseBody
	public Map<String, Object> delete(@PathVariable String id,
			HttpServletRequest request) {
		Map<String, Object> model = new HashMap<String, Object>();
		try {
			productBrandService.deleteById(id);
			model.put(Constants.AJAX_MSG_NAME, Constants.AJAX_MSG_SUCC);
		} catch (Exception e) {
			model.put(Constants.AJAX_MSG_NAME, Constants.AJAX_MSG_ERROR);
			log.error(e);
		}
		return model;
	}

	@RequestMapping(Constants.MV_URI_COMM_DELETBATCH + "/{ids}")
	@ResponseBody
	public Map<String, Object> deleteBatch(@PathVariable String ids,
			HttpServletRequest request) {
		Map<String, Object> model = new HashMap<String, Object>();
		model.put(Constants.AJAX_MSG_NAME, Constants.AJAX_MSG_SUCC);
		List<Serializable> temps = new ArrayList<Serializable>();
		try {
			for (String id : ids.split("_")) {
				if (id != null && !id.equals("")) {
					temps.add(id);
				}
			}
			productBrandService.deleteBatch(temps);
		} catch (Exception e) {
			model.put(Constants.AJAX_MSG_NAME, Constants.AJAX_MSG_ERROR);
			log.error(e);
		}

		return model;
	}

	@RequestMapping(Constants.MV_URI_COMM_DETAIL + "/{id}")
	public ModelAndView detail(@PathVariable String id) {
		ModelAndView mv = new ModelAndView();
		ProductBrand item = productBrandService.findById(id);
		initDetail(mv, item, ROOT_URI, ROOT_VIEW);
		return mv;
	}
	@RequestMapping(Constants.MV_URI_COMM_MODIFY + "/{id}/{attr}/{val}")
	@ResponseBody
	public Map<String, Object> modify(@PathVariable String id,@PathVariable String attr,@PathVariable Integer val,
			HttpServletRequest request) {
		Map<String, Object> model = new HashMap<String, Object>();
		String sql="update ProductBrand  set "+attr+"="+val+" where id='"+id+"'";
		try {
			productBrandService.excuteSql(sql);
			model.put(Constants.AJAX_MSG_NAME, Constants.AJAX_MSG_SUCC);
		} catch (Exception e) {
			model.put(Constants.AJAX_MSG_NAME, Constants.AJAX_MSG_ERROR);
			e.printStackTrace();
			log.error(e);
		}
		return model;
	}

	@RequestMapping(value = Constants.MV_URI_COMM_LIST
			+ "/{parentId}/{from}/{pageSize}/{startIndex}")
	public ModelAndView list(@PathVariable Integer parentId,@PathVariable String from,
			 @PathVariable Integer pageSize,
			@PathVariable Integer startIndex, @ModelAttribute ProductBrand bean,
			HttpServletRequest request) {
		DetachedCriteria dc = DetachedCriteria.forClass(ProductBrand.class);
		ModelAndView mv = new ModelAndView();
		ProductBrand temp = new ProductBrand();
		if (from.equals(Constants.PAGE_ENTRY_TYPE_FORM)) {
			temp = bean;
			request.getSession().setAttribute(ENTITY_SESSION_BEAN, bean);
		}
		if (from.equals(Constants.PAGE_ENTRY_TYPE_PAGE)) {
			if (request.getSession().getAttribute(ENTITY_SESSION_BEAN) != null) {
				temp = (ProductBrand) request.getSession().getAttribute(
						ENTITY_SESSION_BEAN);
			}
		}
		if (from.equals(Constants.PAGE_ENTRY_TYPE_MENU)) {

		}
		if (parentId != 0) {
			dc.add(Restrictions.eq("categoryId", parentId));
		}
		if (pageSize == 0) {
			pageSize = Constants.DEFAULT_PAGESIZE;
		}
		if (bean.getBkw() != null && !bean.getBkw().equals("")) {
			dc.add(Restrictions.like("name", "%" + bean.getBkw() + "%"));
		}
		if (bean.getStartTime() != null && bean.getEndTime() != null) {
			dc.add(Restrictions.ge("addTime", bean.getStartTime()));
			dc.add(Restrictions.le("addTime", bean.getEndTime()));
		}
		if (bean.getStartTime() != null && bean.getEndTime() == null) {
			dc.add(Restrictions.ge("addTime", bean.getStartTime()));
		}
		if (bean.getStartTime() == null && bean.getEndTime() != null) {
			dc.add(Restrictions.le("addTime", bean.getEndTime()));
		}
		dc.addOrder(Order.desc("addTime"));
		Page page = productBrandService.findPageByCriteria(dc, pageSize, startIndex);
		if (pageSize != 0) {
			page.setPageSize(pageSize);
		}
		request.getSession().setAttribute(
				CmsConstants.ONLINE_PRODUCT_CATEGORY_ID,
				parentId == 0 ? 0 : parentId);
		temp.setHightLight(Constants.HIGHTLIGHT_PREFIX + bean.getBkw()
				+ Constants.HIGHTLIGHT_SUFFIX);
		String pageURI=request.getContextPath()+Constants.SYM_PATH_SEPARATOR+ROOT_URI+Constants.MV_URI_COMM_LIST+Constants.SYM_PATH_SEPARATOR+parentId;
		initList(mv,page,Constants.MV_VIEW_LIST,pageURI,ROOT_URI,temp,ROOT_VIEW,-1,pageSize,startIndex);
		return mv;
	}

	/**
	 * @Description: 发布文章的图片上传 kindeditor专用
	 * @author:jemmyee@gmail.com
	 * @date:2011-7-29
	 */
	@RequestMapping("/upload")
	public void upload(@RequestParam MultipartFile imgFile,
			HttpServletRequest request, HttpServletResponse response) {
		response.setContentType("text/html; charset=UTF-8");
		// 定义允许上传的文件扩展名
		String[] fileTypes = new String[] { "gif", "jpg", "jpeg", "png", "bmp" };
		// 最大文件大小
		long maxSize = 1000000;
		String savePath = Constants.UPLOAD_IMAGES_PATH
				+ DateUtils.parseDateToString(new Date(),
						DateUtils.DATE_FORMAT_YYMMDD) + "/";// 文件目录
		String fileName = imgFile.getOriginalFilename();// 文件名
		String dirPath=getAppRoot(request) + savePath;
		if(!FileUtils.isFileExist(dirPath))
		{
			File dir=new File(dirPath);
			dir.mkdirs();
		}
		String path = dirPath + fileName;// 上传文件的绝对路径
		String url = getWebRoot(request) + savePath + fileName;// 前台浏览图片路径
        String relativePath=savePath+fileName;//相对路径 /upload/images/....
		PrintWriter out = null;
		try {
			out = response.getWriter();
		} catch (IOException e1) {
			e1.printStackTrace();
		}

		// 检查目录
		File dirFile = new File(savePath);
		if (!dirFile.exists()) {
			dirFile.mkdirs();
		}
		// 检查目录写权限
		if (!dirFile.canWrite()) {
			out.println(getUploadError("上传目录没有写权限。"));
			return;
		}
		// 检查扩展名
		String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1)
				.toLowerCase();
		if (!Arrays.<String> asList(fileTypes).contains(fileExt)) {
			out.println(getUploadError("该图片格式不支持上传!"));
			return;
		}
		if (imgFile.getSize() > maxSize) {
			out.println(getUploadError("图片大小超出限制!"));
			return;
		}
		FileOutputStream fos;
		try {
			byte[] bytes = imgFile.getBytes();
			fos = new FileOutputStream(path);
			fos.write(bytes);
		} catch (FileNotFoundException e) {
			out.println(getUploadError("上传文件失败"));
			e.printStackTrace();
		} catch (IOException e) {
			out.println(getUploadError("上传文件失败"));
			e.printStackTrace();
		}
		JSONObject obj = new JSONObject();
		obj.put("error", 0);// 0表示上传成功
		obj.put("url", url);
		obj.put("path",path);
		out.println(obj.toJSONString());
		out.println("<script src='"+getWebRoot(request)+"/static/jquery/jquery-1.4.2.min.js' type='text/javascript'></script>");
		out.println("<script src='"+getWebRoot(request)+"/static/jquery/colorbox/jquery.colorbox-min.js' type='text/javascript'></script>");
		out.println(" <script type='text/javascript'>parent.$('uploadView').colorbox.close();parent.$('#img').val('"+relativePath+"')</script>");
	}

	/**
	 * @Description:图片上传错误处理
	 * @author:jemmyee@gmail.com
	 * @date:2011-7-29
	 */
	private String getUploadError(String msg) {
		JSONObject obj = new JSONObject();
		obj.put("error", 1);
		obj.put("message", msg);
		return obj.toJSONString();
	}

}
